package com.cswnode.demo.controller;

import com.cswnode.demo.service.LoginService;
import com.cswnode.demo.util.Constant;
import com.cswnode.demo.util.RedisKeyUtil;
import com.cswnode.demo.util.ResponseVo;
import com.cswnode.demo.util.Utils;
import com.cswnode.demo.vo.loginVo;
import com.google.code.kaptcha.Producer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * @author csw
 * @create 2021/1/26 11:12
 */
@Api(tags = "登录模块")
@RestController
public class LoginController implements Constant {

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private Producer kaptchaRroduct;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    @Autowired
    private LoginService loginService;

    @Value("server.servlet.context-path")
    private String contextPath;

    /**
     * 登录
     * @param user
     * @param cookie
     * @return
     */
    @ApiOperation(value = "登录>登录之后返回token")
    @PostMapping("/login")
    public ResponseVo login(@RequestBody loginVo user, @CookieValue("KaptchaOwner")String cookie,
                            HttpServletRequest request){
        String kaptcha = null;
        if (StringUtils.isNotBlank(cookie)){
            String redisKey = RedisKeyUtil.getKaptcha(cookie);
            kaptcha = redisTemplate.opsForValue().get(redisKey);
        }
        if (StringUtils.isBlank(user.getCode()) || StringUtils.isBlank(kaptcha) || !(user.getCode().equalsIgnoreCase(kaptcha))){
            return ResponseVo.error("验证码输入错误！");
        }
        Map<String, String> result = loginService.login(user,request);
        if (result.containsKey("errorMsg")){
            return ResponseVo.error(result.get("errorMsg"));
        }
        if (result.containsKey("token")){
            return ResponseVo.success("登录成功！",result);
        }
        return ResponseVo.error("未知错误");
    }

    /**
     * 获取验证码
     * @param response
     */
    @ApiOperation(value = "获取验证码")
    @GetMapping("/kaptcha")
    public void getKaptcha(HttpServletResponse response){
        //生成随机的字符串
        String text = kaptchaRroduct.createText();
        System.out.println("验证码："+text);
        //绘制字符串的验证码图片
        BufferedImage image = kaptchaRroduct.createImage(text);
        //验证码归属
        String KaptchaOwner = Utils.GetUUID();
        Cookie cookie = new Cookie("KaptchaOwner",KaptchaOwner);
        //设置cookie存在时间
        cookie.setMaxAge(60);
        //设置cookie生效路劲
        cookie.setPath(contextPath);
        //添加cookie
        response.addCookie(cookie);
        //将验证码存入redis
        String redisKey = RedisKeyUtil.getKaptcha(KaptchaOwner);
        redisTemplate.opsForValue().set(redisKey,text,60, TimeUnit.SECONDS);
        //将生成的图片输入到浏览器
        response.setContentType("image/png");
        try {
            OutputStream outputStream = response.getOutputStream();
            ImageIO.write(image,"png",outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @ApiOperation(value = "退出登录")
    @GetMapping("/logout")
    public ResponseVo logout(){
        return ResponseVo.success("注销成功");
    }


}
